package dao;

import model.TUser;
import utils.DataUtil;

import java.sql.ResultSet;

public class UserDAOImpl implements UserDAO{

    DataUtil dataUtil = null;
    public UserDAOImpl(){
        dataUtil = new DataUtil();
    }
    /**
     * 用户登录操作方法
     *
     * @param userid
     * @param pwd
     * @return 成功则返回VUser，失败返回null
     */
    @Override
    public TUser login(String userid, String pwd) {
        String sql = "select * from t_user where userid = ? and pwd = ?";
        Object [] para = {userid,pwd};
        ResultSet rs = dataUtil.select(sql,para);
        TUser tUser = new TUser(rs);
        return tUser;
    }

    /**
     * 检查某userid是否可用（已经存在就不可用）
     *
     * @param userid
     * @return 可用（数据库中没有）返回true， 否则返回false
     */
    @Override
    public boolean isUseridValid(String userid) {
        String sql = "select * from t_user where userid = ?";
        Object [] para = {userid};
        ResultSet rs = dataUtil.select(sql,para);
        TUser tUser = new TUser(rs);
        if(tUser.getUserid()==null){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 注册用户（添加一个新用户）
     *
     * @param user
     * @return boolean  成功返回true, 失败返回false
     */
    @Override
    public boolean addUser(TUser user) {
        String sql = "insert into t_user(userid,username,pwd,phone,utid)" +
                "values(?,?,?,?,?)";
        Object [] para = {user.getUserid(),user.getUsername(),user.getPwd(), user.getPhone(),user.getUtid()};
        int a = dataUtil.insert(sql,para);
        if(a>0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 修改一个用户信息
     *
     * @param user
     * @return boolean  成功返回true,失败返回false
     */
    @Override
    public boolean modUser(TUser user) {
        String sql = "update t_user set username = ?,pwd = ?, phone = ? where userid = ?";
        Object [] para = {user.getUsername(),user.getPwd(),user.getPhone(),user.getUserid()};
        int a = dataUtil.update(sql,para);
        if(a>0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 根据userid返回一个TUser类型的用户对象
     *
     * @param userid
     * @return TUser   失败返回null
     */
    @Override
    public TUser getTUserByid(String userid) {
        String sql = "select * from t_user where userid = ?";
        Object [] para = {userid};
        ResultSet rs = dataUtil.select(sql,para);
        TUser tUser = new TUser(rs);
        return tUser;
    }
}
